package cn.smvc.sys.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;

import cn.smvc.common.cache.Cache;
import cn.smvc.common.cache.CacheManager;
import cn.smvc.common.web.BaseServlet;
import cn.smvc.sys.entity.SysUser;
import cn.smvc.sys.service.SysUserService;

@WebServlet("/login")
public class LoginServlet extends BaseServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 4060984362128007158L;
	@Autowired
	private SysUserService sysUserService;

	
	public void execute(HttpServletRequest request, HttpServletResponse response) 
			throws IOException, ServletException {
		System.out.println("execute......");
		
		
//		response.setCharacterEncoding("UTF-8");
//		response.setContentType("application/json; charset=utf-8");
//		PrintWriter out = response.getWriter();
		
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("success", false);
		result.put("msg", "");
		
		String code = request.getParameter("code");
		if(StringUtils.isNotEmpty(code)) {
			Cache cache = CacheManager.getCacheInfo(code);
			if(cache != null && !cache.isExpired()) {
				String userId = (String) cache.getValue();
				if(StringUtils.isNotEmpty(userId)) {
					SysUser user = sysUserService.get(userId);
					if(user != null) {
						request.getSession().setAttribute("user", user);
						result.put("success", true);
						result.put("msg", "");
						
						response.sendRedirect("index");
//						request.getRequestDispatcher("index").forward(request, response);
					} else {
						result.put("msg", "用户不存在");
					}
					
				} else {
					result.put("msg", "用户id不存在");
				}
			} else {
				result.put("msg", "code已过期");
			}
		} else {
			result.put("msg", "code不存在");
		}
		System.out.println(JSON.toJSONString(result));
//		out.println(JSON.toJSONString(result));
		
	}
}
